#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;
use feature qw(say);
use Readonly;

use lib "$ENV{SKAL_ROOT}/lib";
use Users;

my $param = shift // die "Not defined what to do! Use the 'help' parameter\n";

Readonly(my $WARNING_TEXT => <<END_OF_WARNING_TEXT);
Username contains some unauthorized characters. Allowed characters are all
alphanumeric characters and a '_' character, but not two or more '_'
characters in a row.
END_OF_WARNING_TEXT

my $usr;

if ($param eq 'add') {
    my $new_username = do_input_username('New username');
    $usr = Users->new;
    my $exs = $usr->user_exists($new_username);
    if ($exs == -1) {
        do_warning_exit($WARNING_TEXT);
    }
    if ($exs == 0) {
        # Username does not exist
        $usr->add($new_username, do_input_password('New password'));
        $usr->disconnect;
        exit 0;
    }
    if ($exs == 1) {
        do_warning_exit('Username already exists. Choose different.');
    }
}
elsif ($param eq 'del') {
    my $username = do_input_username('Username to delete');
    $usr = Users->new;
    my $exs = $usr->user_exists($username);
    if ($exs == -1) {
        do_warning_exit($WARNING_TEXT);
    }
    if ($exs == 0) {
        do_warning_exit('Username does not exist.');
    }
    if ($exs == 1) {
        # Username exists
        $usr->del($username);
        $usr->disconnect;
        exit 0;
    }
}
elsif ($param eq 'pass') {
    my $username = do_input_username('Username to change password to');
    $usr = Users->new;
    my $exs = $usr->user_exists($username);
    if ($exs == -1) {
        do_warning_exit($WARNING_TEXT);
    }
    if ($exs == 0) {
        do_warning_exit('Username does not exist. Choose different.');
    }
    if ($exs == 1) {
        # Username exists
        $usr->pass($username, do_input_password('Changed password'));
        $usr->disconnect;
        exit 0;
    }
}
elsif ($param eq 'help') {
    $usr = Users->new;
    do_help_list($usr->help);
}
elsif ($param eq 'list') {
    $usr = Users->new;
    do_help_list($usr->list);
}
else {
    say q{Unknown parameter! Use the 'help' parameter};
    exit 1;
}

# Help
# List
sub do_help_list {
    my $text = shift;

    $usr->disconnect;
    say $text;
    exit 0;
}

sub do_input_username {
    my $text = shift;

    print "$text: ";
    my $username = <>;
    chomp $username;
    return $username;
}

sub do_input_password {
    my $text = shift;

    print "$text: ";
    system 'stty -echo';
    my $password = <>;
    system 'stty echo';
    print "\n";
    chomp $password;
    return $password;
}

# Username (already) exists
# Username does not exist
# Username contains unauthorized characters
sub do_warning_exit {
    my $text = shift;

    $usr->disconnect;
    say $text;
    return exit 1;
}

